package overview;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class MySQL {
	// JDBC driver name and database URL
	   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
	   static final String DB_URL = "jdbc:mysql://localhost/test";
	public static void main(String[] args) {
		 
		   
		   try {
			   Class.forName(JDBC_DRIVER);
		   }catch (ClassNotFoundException ex){
			   ex.printStackTrace();
		   }
		   
		   try (Connection con = DriverManager.getConnection(DB_URL);
				   PreparedStatement ps = createPreparedStatement(con);
				   ResultSet rs = ps.executeQuery();) {
		      
	    	  while(rs.next()){
			         //Retrieve by column name
			         int id  = rs.getInt("id");
			         int age = rs.getInt("age");
			         String first = rs.getString("first");
			         String last = rs.getString("last");

			         //Display values
			         System.out.print("ID: " + id);
			         System.out.print(", Age: " + age);
			         System.out.print(", First: " + first);
			         System.out.println(", Last: " + last);
			      }
		   }catch(SQLException se){
		      //Handle errors for JDBC
		      se.printStackTrace();
		   }
		   
		   System.out.println("Goodbye!");

	}
	private static PreparedStatement createPreparedStatement(Connection con) throws SQLException {
		String sql = "SELECT id, first, last, age FROM emp";
	    PreparedStatement ps = con.prepareStatement(sql);
	    return ps;
	}
}
